package com.kitty.common.schedule;


import com.kitty.common.cache.RedisService;
import com.kitty.common.start.GameServer;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.activity.service.other.*;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.activity.service.task.XuanShangTaskHandler;
import com.kitty.game.chat.message.RespChat;
import com.kitty.game.common.BoosTitleDeal;
import com.kitty.game.config.NPC;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.equip.service.HDDSService;
import com.kitty.game.equip.service.NewChargeActivityService;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.bean.FightObject;
import com.kitty.game.fight.service.FightExecutorService;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.mail.service.MailService;
import com.kitty.game.newchoujiang.service.NewChouJiangService;
import com.kitty.game.notice.model.Notice;
import com.kitty.game.pk.message.RespReleasePrisonerSuccess;
import com.kitty.game.pk.service.PkService;
import com.kitty.game.player.PlayerService;
import com.kitty.game.rank.service.RankService;
import com.kitty.game.rank.service.handler.MonthTaoRankHandler;
import com.kitty.game.rank.service.handler.PetRankHandler;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.task.service.taskHandler.DugeonTaskHandler;
import com.kitty.game.utils.ChatConst;
import com.kitty.game.utils.SenderUtils;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.welfare.service.OnlineRewardHandler;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.task.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/*时间定时器*/
@Component
@Slf4j
public class ScheduledService {

    @Autowired
    Dao dao;
    @Autowired
    ServerService serverService;
    @Autowired
    EquipService equipService;
    @Autowired
    GameServer gameServer;
    @Autowired
    RoleService roleService;
    @Autowired
    PlayerService playerService;
    @Autowired
    FightService fightService;
    @Autowired
    MailService mailService;

    @Autowired
    NewChargeActivityService newChargeActivityService;
    @Autowired
    RedisService redisService;


    @Scheduled(cron = "0 35 23 * * ?")
    public void yuanbao() {
        ConcurrentHashMap<Long, Long> moduleId_count = new ConcurrentHashMap<>(serverService.getModuleId_count());
        ArrayList<NutMap> arrayList = new ArrayList<>();
        log.error("协议请求数量========");
        log.error("协议请求数量========");
        for (Map.Entry<Long, Long> entry : moduleId_count.entrySet()) {
            if (entry.getValue() >= 100000) {
                NutMap nutMap = new NutMap();
                nutMap.setv("moduleId", entry.getKey());
                nutMap.setv("count", entry.getValue());
                arrayList.add(nutMap);
            }
        }
        Collections.sort(arrayList, new Comparator<NutMap>() {
            @Override
            public int compare(NutMap o1, NutMap o2) {
                if (o1.getLong("count", 0) > o2.getLong("count", 0)) {
                    return -1;
                }
                return -1;
            }
        });
        log.error("协议请求数量========{}", Json.toJson(arrayList, JsonFormat.compact()));
    }


    /**
     * 定时boos回收称号
     */

    public void recycleTitle() {
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("mltt");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("mlzs");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("mlzy");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("mlzz");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("mlzw");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("drjw");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jydd");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("sldd");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("xldd");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("zwdd");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("tyj");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("tnz");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("tkx");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("ttbjx");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("tlj");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("tlzz");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("td");

        //2022-06-11新增
        //七杀
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("qisha");
        //九天
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_hao");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_yang");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_chi");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_zhu");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_cheng");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_you");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_xuan");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_bian");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("jiutian_jun");
        //超级boss
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("hxyh");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("xlmz");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("myxh");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("cxgy");
        SpringUtils.getBean(BoosTitleDeal.class).clearKeyAndTitleAndRoleBoosTitle("zyyh");
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void shuadaoOffline() {
        RoleService roleService = SpringUtils.getRoleService();
        Map<Long, IoSession> map = SpringUtils.getBean(GameServer.class).getAcceptor().getManagedSessions();
        for (Map.Entry<Long, IoSession> entry : map.entrySet()) {
            IoSession session = entry.getValue();
            Role tempRole = SessionUtils.getRoleBySession(session);
            if (tempRole == null) {
                continue;
            }
            if (System.currentTimeMillis() - tempRole.getOfflineNotice().getLastTime() > 5 * TimeUtil.ONE_MINUTE && tempRole.getOfflineNotice().getShuadao() == 1) {
                roleService.sendShuadaoStauts(tempRole);
                log.error("离线刷道提示奖励=={}", tempRole.getName());
            }
        }
    }
    //发送充值排行榜公告
    @Scheduled(cron = "0 0/5 * * * ?")
    public void noticeChongZhi() {
        newChargeActivityService.notice(true);
    }

//    //抽奖发放奖励
//    @Scheduled(cron = "0 55 23 * * ?")
//    public void noticeChoujiang() {
//        String curr = DateUtils.formatDate(new Date());
//        if (!choujiangService.getChoujiangDay().getData().startsWith(curr)) {
//            return;
//        }
//        for (int i = 1; i < 10; i++) {
//            int time = i * 60;
//            if (i <= 5) {
//                serverService.getScheduledExecutorService().schedule(new Runnable() {
//                    @Override
//                    public void run() {
//                        choujiangService.notice111(true);
//                    }
//                }, time, TimeUnit.SECONDS);
//            } else {
//                serverService.getScheduledExecutorService().schedule(new Runnable() {
//                    @Override
//                    public void run() {
//                        choujiangService.notice111(true);
//                    }
//                }, time, TimeUnit.SECONDS);
//            }
//
//        }
//        // 延时6分钟后发奖励
//        serverService.getScheduledExecutorService().schedule(new Runnable() {
//            @Override
//            public void run() {
//                choujiangService.sendReward();
//            }
//        }, 6 * 60, TimeUnit.SECONDS);
//    }
//    @Scheduled(cron = "0/10 * * * * ?")
//    public void findAllFight() {
//        ConcurrentHashMap<Integer, Fight> fights = FightExecutorService.FIGHTS;
//        System.out.println("现在有几个战场："+fights.size());
//        for (Map.Entry<Integer, Fight> integerIntegerEntry : fights.entrySet()) {
//            System.out.println("现在的战场："+integerIntegerEntry.getKey());
//        }
//
//    }

    //公告发送定时任务
    @Scheduled(cron = "0 0/10 * * * ?")
    public void notice() {
        Notice notice = dao.fetch(Notice.class, Cnd.where("id", "=", 1));
        if (notice == null) {
            return;
        }
        RespChat respChat = new RespChat();
        respChat.setMsg(notice.getContent());
        respChat.setList(new ArrayList<>());
        respChat.setRoleName("公告");
        respChat.setLineName(serverService.getServer().getSonName());
        respChat.setRoleId(0);
        respChat.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
        respChat.setType(ChatConst.ADNOTICE);
        SenderUtils.pushChatMessage(respChat);
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void prison() {
        PkService pkService = SpringUtils.getBean(PkService.class);
        List<Role> prisonRoles = pkService.getPrisonRoles();
        for (Role role : prisonRoles) {
            if (role.getPkInfoBox().getPrisonTime() > 0) {
                if (role.getPkInfoBox().getPrisonTime() <= System.currentTimeMillis() / 1000) {
                    /**放出监狱*/
                    pkService.removeFromPrison(role);
                }
                role.save();
            }
            MessagePusher.pushMessage(role, new RespReleasePrisonerSuccess(role.getGid()));
        }
    }


    @Scheduled(cron = "0 0/1 * * * ?")
    public void delNpc() {
        NPC npc = null;
 /*       ConcurrentHashMap<Integer, NPC> map = new ConcurrentHashMap<>(DataCache.TASK_NPCS);
        for (Map.Entry<Integer, NPC> entry : map.entrySet()) {
            npc = entry.getValue();*/
        /**已经过结束时间时，删除NPC*/
 /*           if (npc.getEndTime() > 0 && System.currentTimeMillis() > npc.getEndTime()) {
                bossService.delTaskNpc(entry.getValue());
                log.error("删除npc====={}=={}=={}=={}=={}={}",npc.getName(),npc.getId(),npc.getMapId(),npc.getEndTime()<System.currentTimeMillis());
            }
        }*/

        /**掌门、证道殿、英雄会战斗状态超过30分钟后清空*/
        long now = System.currentTimeMillis();
        List<Integer> npcIds = Arrays.asList(13788, 13871, 13916, 14567, 14609, 16208, 16210, 16212, 16214, 16216, 16218, 16220, 16222, 16224, 16226, 16228, 16230, 16232, 16234, 16236, 16238, 16272, 16274, 16276, 16278, 16280, 16282, 16284, 16286, 16288, 16290, 16292, 16294, 16296, 16298, 16300, 16302, 16336, 16338, 16340, 16342, 16344, 16346, 16348, 16350, 16352, 16354, 16356, 16358, 16360, 16362, 16364, 16366, 16400, 16402, 16404, 16406, 16408, 16410, 16412, 16414, 16416, 16418, 16420, 16422, 16424, 16426, 16428, 16430, 16464, 16466, 20819, 20821, 20823, 20825, 20827, 20499, 20501, 20503, 20505, 20507, 20695, 20697, 20699, 20701, 20703, 20519, 20521, 20523, 20525, 20527, 20561, 20563, 20565, 20567, 20569, 20757, 20759, 20761, 20763, 20765, 20653, 20655, 20689, 20691, 20693, 20581, 20583, 20585, 20587, 20589, 20457, 20459, 20461, 20463, 20497, 20447, 20449, 20451, 20453, 20455, 20509, 20511, 20513, 20515, 20517, 20571, 20573, 20575, 20577, 20579, 20767, 20769, 20771, 20773, 20775, 20777, 20779, 20781, 20783, 20817, 20705, 20707, 20709, 20711, 20713, 20591, 20625, 20627, 20629, 20631, 20437, 20439, 20441, 20443, 20445, 20643, 20645, 20647, 20649, 20651, 88892, 88893, 88894);
        for (int npcId : npcIds) {
            npc = SpringUtils.getMapService().getNpc(npcId);
            if (npc == null) {
                continue;
            }
            if (!npc.isInFight()) {
                continue;
            }
            if ((npc.getCreateTime() + 30 * TimeUtil.ONE_MINUTE) > now) {
                continue;
            }

            npc.setInFight(false);
           // LoggerFunction.ACTIVITY.getLogger().warn("{}的创建时间为{}, 修改战斗状态为false", npcId, npc.getCreateTime());
        }
    }

    /**
     * 刷新经验精灵
     * 每5分钟刷一次
     */
//    @Scheduled(cron = "0 0/30 * * * ?")
//    public void flushJinyanhuanj() {
//        StopWatch stopWatch = new StopWatch();
//        stopWatch.start();
//
//        SpringUtils.getBean(UpLevelJlHandler.class).flushPirate();
//
//        stopWatch.stop();
//        log.warn("升级幻境开始，用时{}毫秒", stopWatch.getTime());
//    }

//    /**
//     * 刷新镇妖塔
//     * 每30分钟刷一次
//     */
//    @Scheduled(cron = "0 0/5 * * * ?")   /*每30分钟*/
//    public void flushzhenyao() {
//        StopWatch stopWatch = new StopWatch();
//        stopWatch.start();
//
//        SpringUtils.getBean(ZhenYaoPagodaHandler.class).flushPirate();
//
//        stopWatch.stop();
//        log.warn("镇妖塔妖怪刷新，用时{}毫秒", stopWatch.getTime());
//    }


    @Scheduled(cron = "0 0/5 * * * ?")
    public void delFight() {
        //Logger logger = LoggerFunction.FIGHT.getLogger();
        int before = FightExecutorService.FIGHTS.size();

        ConcurrentHashMap<Integer, Fight> map = new ConcurrentHashMap<>(FightExecutorService.FIGHTS);
        long now = System.currentTimeMillis();
        for (Map.Entry<Integer, Fight> entry : map.entrySet()) {
            Fight fight = entry.getValue();
            if (entry.getValue().getCreateTime() + 60 * TimeUtil.ONE_MINUTE < now) {
                // 超过半小时删除战场
                log.error("超过半小时删除战场");
                for (FightObject fightObject : fight.getAllFightObjects()) {
                    fightService.quiteFight(fight, fightObject, false);
                }
                fightService.clearFight(fight);
            }
        }

        int end = FightExecutorService.FIGHTS.size();
        if (end != before) {
            log.error("每五分钟检查一次战场，当前战场数量={}, 删除后数量={}", before, end);
        }
    }

    @Scheduled(cron = "0 0 12 * * ?")
    public void delMail() {
        ArrayList<Long> arrayList = playerService.allUids();
        for (Long uid : arrayList) {
            Role tempRole = playerService.getPlayerBy(uid);
            mailService.delMail(tempRole);
        }
    }

    @Scheduled(cron = "0 0 16 * * ?")
    public void delMail1() {
        ArrayList<Long> arrayList = playerService.allUids();
        for (Long uid : arrayList) {
            Role tempRole = playerService.getPlayerBy(uid);
            mailService.delMail(tempRole);
        }
    }

    @Scheduled(cron = "0 0 21 * * ?")
    public void delMail2() {
        ArrayList<Long> arrayList = playerService.allUids();
        for (Long uid : arrayList) {
            Role tempRole = playerService.getPlayerBy(uid);
            mailService.delMail(tempRole);
        }
    }
    /**
     * 每日重置时间点(5点零2)
     */
    @Scheduled(cron = "0 2 0 * * ?")
    public void dailyFiveReset() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        /**遍历在线玩家*/
        Collection<Role> roles = DataCache.ONLINE_ROLES.values();
        for (Role role : roles) {
            ThreadLocalUtil.addLocalTask(role, () -> roleService.doDailyFiveReset(role));
        }

        stopWatch.stop();
        log.info("5点重置玩家数据，用时{}毫秒", stopWatch.getTime());
    }
    /**
     * 充值每日累计充值领取记录
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void dailyFiveReset2() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        /**遍历在线玩家*/
        Collection<Role> roles = DataCache.ONLINE_ROLES.values();
        for (Role role : roles) {
            ThreadLocalUtil.addLocalTask(role, () -> roleService.doDailyFiveReset2(role));
        }

        stopWatch.stop();
        log.info("12点重置玩家数据，用时{}毫秒", stopWatch.getTime());
    }

    /**
     * 每月重置
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    public void monthReset() {
    }

    /**
     * 每周重置
     */
    @Scheduled(cron = "0 0 5 * * MON")
    public void weekReset() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        /**重置排行榜*/
        SpringUtils.getBean(MonthTaoRankHandler.class).resetMonthRank();
        SpringUtils.getBean(PetRankHandler.class).resetMonthRank();

        /**遍历在线玩家*/
        Collection<Role> roles = DataCache.ONLINE_ROLES.values();
        for (Role role : roles) {
            ThreadLocalUtil.addLocalTask(role, () -> roleService.doWeeklyReset(role));
        }

        stopWatch.stop();
        log.info("每周重置数据，用时{}毫秒", stopWatch.getTime());
    }

    /**
     * 每半小时执行一次
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void halfHour() {
        int minute = Calendar.getInstance().get(Calendar.MINUTE);
        if (minute == 30) {
            /**可以开始接取悬赏任务*/
            SpringUtils.getBean(XuanShangTaskHandler.class).pushStartAcceptSystem();
        }
//        if (minute == 0) {
//            SpringUtils.getBean(DevilActivityHandler.class).sendSystem();
//        }

        /**试道大会每半小时的系统提示*/
//        SpringUtils.getBean(ShiDaoHandler.class).sendNotice();
//        SpringUtils.getBean(OnlineRewardHandler.class).sendSystem();
//        SpringUtils.getBean(ShangGuBossHandler.class).sendSystem();/*上古*/
//        SpringUtils.getBean(DevilActivityHandler.class).sendAdNotice();/*神魔*/
    }

    /**
     * 上传排行榜数据到登录服
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void uploadRankToLogin() {
        SpringUtils.getBean(RankService.class).uploadRankToLogin();
        SpringUtils.getBean(RankService.class).uploadRankViewToLogin();
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkParty() {
        SpringUtils.getPartyService().check();
    }

    /**
     * 定时检测玩家，比如多久后没有心跳则离队
     */
    @Scheduled(cron = "0/1 * * * * ?")
    public void checkRole() {
        SpringUtils.getRoleService().checkOffline();
    }

    /**
     * 删除超时副本
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void delDugeonData() {
        SpringUtils.getBean(DugeonTaskHandler.class).checkDugeon();
    }

    /**
     * 初始化在线奖励生效时间区间
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void initOnlineRewardTimeRange() {
        SpringUtils.getBean(OnlineRewardHandler.class).initTime();
    }


    /**
     * 定时发送充值
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void sendChongZhi() {
        SpringUtils.getBean(HDDSService.class).getChangeAll();
    }
//
//    /**
//     * 刷新变异星君
//     */
//    @Scheduled(cron = "0 0 0/1 * * ?")
//    public void flushbianyixingjun() {
//        SpringUtils.getBean(VariantStarHandler.class).flushNpc();
//    }


//
//    /**
//     * 试道
//     */
//    @Scheduled(cron = "0 0 19 * * ?")
//    public void flushShidao() {
//        SpringUtils.getBean(ShiDaoHandler.class).loadCommon();
//    }

    /**
     * 开启试道
     */
//    @Scheduled(cron = "0 50 20 * * ?")
//    public void notifyShidao() {
//        SpringUtils.getBean(ShiDaoHandler.class).notifyShidao();
//    }

    /**
     * 开启跨服试道
     */
//    @Scheduled(cron = "0 16 20 * * ?")//
//    public void kuafuShidao() {
//        SpringUtils.getBean(ShiDaoHandler.class).kuafuShidao();
//    }

   /* 重置每天充值30为3倍的状态
    @Scheduled(cron = "0 0 0 * * ?")
    public void dailyCharge30Reset() {

    	StopWatch stopWatch = new StopWatch();
        stopWatch.start();*/

    /**遍历所有玩家*/
/*    	ConcurrentHashMap<Long, Role> tempMap = new ConcurrentHashMap<>();
    	tempMap.putAll(DataCache.ONLINE_ROLES);
    	tempMap.putAll(DataCache.OFFLINE_ROLES);

        Collection<Role> roles = tempMap.values();
        for (Role role : roles) {
            ThreadLocalUtil.addLocalTask(role, () ->  role.getActivity().daily0Reset());
        }
        stopWatch.stop();
        log.warn("0点重置玩家充值30送3倍的状态，用时{}毫秒", stopWatch.getTime());

    }*/



}
